{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "f5e03f74-282a-48f3-8e22-6ceccce3763c",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "# Semantic Search"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8e384231-52c7-4630-b849-01cfb4af59c9",
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting openai\n",
      "  Downloading openai-0.27.0-py3-none-any.whl (70 kB)\n",
      "     ---------------------------------------- 70.1/70.1 kB 3.7 MB/s eta 0:00:00\n",
      "Collecting aiohttp\n",
      "  Downloading aiohttp-3.8.4-cp39-cp39-win_amd64.whl (323 kB)\n",
      "     ------------------------------------- 323.6/323.6 kB 10.1 MB/s eta 0:00:00\n",
      "Requirement already satisfied: tqdm in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from openai) (4.64.1)\n",
      "Requirement already satisfied: requests>=2.20 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from openai) (2.28.1)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from requests>=2.20->openai) (2022.9.14)\n",
      "Requirement already satisfied: idna<4,>=2.5 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from requests>=2.20->openai) (3.3)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from requests>=2.20->openai) (1.26.11)\n",
      "Requirement already satisfied: charset-normalizer<3,>=2 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from requests>=2.20->openai) (2.0.4)\n",
      "Collecting yarl<2.0,>=1.0\n",
      "  Downloading yarl-1.8.2-cp39-cp39-win_amd64.whl (56 kB)\n",
      "     ---------------------------------------- 56.8/56.8 kB 2.9 MB/s eta 0:00:00\n",
      "Collecting multidict<7.0,>=4.5\n",
      "  Downloading multidict-6.0.4-cp39-cp39-win_amd64.whl (28 kB)\n",
      "Collecting frozenlist>=1.1.1\n",
      "  Downloading frozenlist-1.3.3-cp39-cp39-win_amd64.whl (34 kB)\n",
      "Requirement already satisfied: attrs>=17.3.0 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from aiohttp->openai) (21.4.0)\n",
      "Collecting aiosignal>=1.1.2\n",
      "  Downloading aiosignal-1.3.1-py3-none-any.whl (7.6 kB)\n",
      "Collecting async-timeout<5.0,>=4.0.0a3\n",
      "  Downloading async_timeout-4.0.2-py3-none-any.whl (5.8 kB)\n",
      "Requirement already satisfied: colorama in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from tqdm->openai) (0.4.5)\n",
      "Installing collected packages: multidict, frozenlist, async-timeout, yarl, aiosignal, aiohttp, openai\n",
      "Successfully installed aiohttp-3.8.4 aiosignal-1.3.1 async-timeout-4.0.2 frozenlist-1.3.3 multidict-6.0.4 openai-0.27.0 yarl-1.8.2\n",
      "Collecting tiktoken\n",
      "  Downloading tiktoken-0.3.0-cp39-cp39-win_amd64.whl (581 kB)\n",
      "     -------------------------------------- 581.4/581.4 kB 6.1 MB/s eta 0:00:00\n",
      "Requirement already satisfied: regex>=2022.1.18 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from tiktoken) (2022.7.9)\n",
      "Requirement already satisfied: requests>=2.26.0 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from tiktoken) (2.28.1)\n",
      "Collecting blobfile>=2\n",
      "  Downloading blobfile-2.0.1-py3-none-any.whl (73 kB)\n",
      "     ---------------------------------------- 73.5/73.5 kB 4.0 MB/s eta 0:00:00\n",
      "Requirement already satisfied: lxml~=4.9 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from blobfile>=2->tiktoken) (4.9.1)\n",
      "Collecting pycryptodomex~=3.8\n",
      "  Downloading pycryptodomex-3.17-cp35-abi3-win_amd64.whl (1.7 MB)\n",
      "     ---------------------------------------- 1.7/1.7 MB 6.5 MB/s eta 0:00:00\n",
      "Requirement already satisfied: urllib3<3,>=1.25.3 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from blobfile>=2->tiktoken) (1.26.11)\n",
      "Requirement already satisfied: filelock~=3.0 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from blobfile>=2->tiktoken) (3.6.0)\n",
      "Requirement already satisfied: charset-normalizer<3,>=2 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from requests>=2.26.0->tiktoken) (2.0.4)\n",
      "Requirement already satisfied: idna<4,>=2.5 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from requests>=2.26.0->tiktoken) (3.3)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from requests>=2.26.0->tiktoken) (2022.9.14)\n",
      "Installing collected packages: pycryptodomex, blobfile, tiktoken\n",
      "Successfully installed blobfile-2.0.1 pycryptodomex-3.17 tiktoken-0.3.0\n"
     ]
    }
   ],
   "source": [
    "!pip install openai\n",
    "!pip install tiktoken\n",
    "!pip install streamlit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d94bb7a6-12be-43f7-b465-95a5e8f2c516",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import re\n",
    "import requests\n",
    "import sys\n",
    "import os\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from openai.embeddings_utils import get_embedding, cosine_similarity\n",
    "from openai.embeddings_utils import distances_from_embeddings\n",
    "\n",
    "\n",
    "openai.api_type = \"azure\"\n",
    "openai.api_key = \"xxx\"\n",
    "openai.api_base = \"xxx\"\n",
    "openai.api_version = \"2022-12-01\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "76075104-6f27-4561-a58d-279c674558f9",
   "metadata": {},
   "source": [
    "# Contracts analyzer and generator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "195d7e03-5a81-43bd-b937-c7c8b740e417",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import re\n",
    "import requests\n",
    "import sys\n",
    "import os\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from openai.embeddings_utils import get_embedding, cosine_similarity\n",
    "from openai.embeddings_utils import distances_from_embeddings\n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "5451f5ba-0def-416d-8f11-8a397e8eb466",
   "metadata": {},
   "source": [
    "## Key clauses extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "5074d4e9-44b3-4b32-a464-84de8cf1d5c1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The termination clause is clause 3 of the Agreement, which states that the Agreement shall continue until 31/12/2023, unless earlier terminated by either party upon 30 days' prior written notice.\n"
     ]
    }
   ],
   "source": [
    "contract = \"\"\"\n",
    "This Contract for Services (\"Agreement\") is entered into as of [date], by and between Company A (\"Company\") and Company B (\"Service Provider\").\n",
    "1.\tServices Provided. Service Provider agrees to provide the following services to Company (the \"Services\"): The Service Provider agrees to provide consulting services to the Company in the field of marketing, including but not limited to market research, development of a marketing strategy, and implementation of marketing campaigns. The Service Provider shall provide reports and recommendations to the Company based on the results of the market research and the agreed-upon marketing strategy.\n",
    "2.\tCompensation. Company shall pay Service Provider the sum of 1.000.000 (One Million) $ for the Services. Payment shall be made on 15/9/2023.\n",
    "3.\tTerm. This Agreement shall commence on 1/5/2023 and continue until 31/12/2023, unless earlier terminated by either party upon 30 days' prior written notice.\n",
    "4.\tIndependent Contractor. Service Provider is an independent contractor, and nothing in this Agreement shall be construed as creating an employer-employee relationship, partnership, or joint venture between the parties.\n",
    "5.\tConfidentiality. Service Provider agrees to keep confidential any and all information learned or obtained as a result of providing the Services to Company. Service Provider shall not disclose such information to any third party without Company's prior written consent.\n",
    "6.\tOwnership of Work Product. Service Provider agrees that any and all work product produced in connection with the Services shall be the sole property of Company.\n",
    "7.\tRepresentations and Warranties. Service Provider represents and warrants that it has the necessary expertise and experience to perform the Services in a professional and workmanlike manner.\n",
    "8.\tIndemnification. Service Provider agrees to indemnify and hold harmless Company, its officers, directors, employees, and agents from and against any and all claims, damages, liabilities, costs, and expenses arising out of or in connection with the Services.\n",
    "9.\tGoverning Law. This Agreement shall be governed by and construed in accordance with the laws of Italy without regard to conflicts of laws principles.\n",
    "10.\tEntire Agreement. This Agreement constitutes the entire agreement between the parties and supersedes all prior or contemporaneous negotiations, agreements, representations, and understandings between the parties, whether written or oral.\n",
    "IN WITNESS WHEREOF, the parties have executed this Agreement as of the date first above written.\n",
    "[Signature block for Company]\n",
    "[Signature block for Service Provider]\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "response = openai.Completion.create(\n",
    "  engine=\"test1\",\n",
    "  prompt= contract + \"what is the termination clause?\",\n",
    "  temperature=0,\n",
    "  max_tokens=1968,\n",
    "  top_p=0.5,\n",
    "  frequency_penalty=0,\n",
    "  presence_penalty=0,\n",
    "  best_of=1,\n",
    "  stop=None)\n",
    "\n",
    "print(response[\"choices\"][0][\"text\"].strip())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "d07d1601-18f9-48c6-98c6-c89878ef3d8e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "you: what is the confidentiality clause?\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "AI Assistant: The confidentiality clause is a clause in the contract that requires the Service Provider to keep confidential any and all information learned or obtained as a result of providing the Services to Company. The Service Provider shall not disclose such information to any third party without Company's prior written consent.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "you: what is the compensation and the due date?\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "AI Assistant: The compensation is 1.000.000 (One Million) $ and the due date is 15/9/2023.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "you: is there an indemnification clause?\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "AI Assistant: Yes, there is an indemnification clause. Service Provider agrees to indemnify and hold harmless Company, its officers, directors, employees, and agents from and against any and all claims, damages, liabilities, costs, and expenses arising out of or in connection with the Services.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "you: q\n"
     ]
    }
   ],
   "source": [
    "prompt = \"<|im_start|>system\\n\" + contract + \"\\n<|im_end|>\\n\"\n",
    "\n",
    "#print('AI Assistant: ' + prompt + '\\n')\n",
    "while True:\n",
    "    \n",
    "    query = input(\"you:\")\n",
    "    if query == 'q':\n",
    "        break   \n",
    "    user_input = \"<|im_start|>user\\n\" + query + \"\\n<|im_end|>\\n<|im_start|>assistant\\n\"\n",
    "    prompt+=user_input\n",
    "    output = openai.Completion.create(\n",
    "          engine=\"test1\",\n",
    "          prompt=prompt,\n",
    "          temperature=0,\n",
    "          max_tokens=2000,\n",
    "          top_p=0.95,\n",
    "          frequency_penalty=0,\n",
    "          presence_penalty=0,\n",
    "          stop=[\"<|im_end|>\"])\n",
    "    print('\\n')\n",
    "    print('AI Assistant: ' + output[\"choices\"][0][\"text\"].strip() + '\\n')\n",
    "    response = output[\"choices\"][0][\"text\"].strip() + \"\\n<|im_end|>\\n\"\n",
    "    prompt+=response"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "07699988-fd9c-4858-99ab-421da20de82e",
   "metadata": {},
   "source": [
    "## Flagging potential issues"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "e6edcf91-d3c9-4cd9-aa63-3aa5f43d5b4a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "There might be some ambiguity in the contract regarding the duties of John Doe. It is not clear what specific responsibilities he will have as the Chief Financial Officer. Additionally, the contract does not state what will happen if either party breaches the agreement. There is also a potential conflict in the terms regarding the severance pay if John Doe is terminated without cause. The contract states that he will receive 12 months' base salary, but it is not clear if this is in addition to the annual salary or if it is included in the annual salary.\n"
     ]
    }
   ],
   "source": [
    "contract = \"\"\"\n",
    "Sample Employment Agreement\n",
    "This Agreement is made between ABC Corporation and John Doe, effective as of the date of employment.\n",
    "1.\tTerm. This Agreement will last for three years and can be renewed upon mutual agreement.\n",
    "2.\tDuties. John Doe will serve as the Company's Chief Financial Officer and perform assigned responsibilities.\n",
    "3.\tCompensation. John Doe will receive an annual salary of $200,000 and will be eligible for the Company's annual bonus program.\n",
    "4.\tTermination. Either party can terminate this Agreement with written notice. If the Company terminates John Doe without cause, he will receive severance pay equal to 12 months' base salary.\n",
    "5.\tNon-Competition. John Doe agrees not to engage in any competitive business or activity for two years following the termination of this Agreement without prior written consent from the Company.\n",
    "6.\tGoverning Law. This Agreement is governed by the laws of the State of Delaware.\n",
    "7.\tEntire Agreement. This Agreement supersedes all prior agreements between the parties.\n",
    "8.\tAmendments. This Agreement cannot be modified except in writing signed by both parties.\n",
    "9.\tCounterparts. This Agreement may be executed in counterparts, each of which shall be deemed an original.\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "response = openai.Completion.create(\n",
    "  engine=\"test1\",\n",
    "  prompt= contract + \"Analyze this contract and tell me whether there might be some ambiguity or conflicting terms.\",\n",
    "  temperature=0,\n",
    "  max_tokens=1968,\n",
    "  top_p=0.5,\n",
    "  frequency_penalty=0,\n",
    "  presence_penalty=0,\n",
    "  best_of=1,\n",
    "  stop=None)\n",
    "\n",
    "print(response[\"choices\"][0][\"text\"].strip())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "1544af42-dc69-4bb2-8ba1-234569269851",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "you: Analyze this contract and tell me whether there might be some ambiguity or conflicting terms.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "AI Assistant: There might be some ambiguity in the \"Duties\" section, as it is not clear what exactly John Doe's responsibilities will be. There could also be a conflict in the \"Compensation\" section if John Doe does not receive the annual bonus that he is expecting.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "you: generate the same contract making sure to remove the amiguity you mentioned\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "AI Assistant: This Agreement is made between ABC Corporation and John Doe, effective as of the date of employment.\n",
      "1.\tTerm. This Agreement will last for three years and can be renewed upon mutual agreement.\n",
      "2.\tDuties. John Doe will serve as the Company's Chief Financial Officer and will perform all duties and responsibilities typically associated with this position, as well as any other duties as may be assigned by the Company from time to time.\n",
      "3.\tCompensation. John Doe will receive an annual salary of $200,000 and will be eligible for the Company's annual bonus program.\n",
      "4.\tTermination. Either party can terminate this Agreement with written notice. If the Company terminates John Doe without cause, he will receive severance pay equal to 12 months' base salary.\n",
      "5.\tNon-Competition. John Doe agrees not to engage in any competitive business or activity for two years following the termination of this Agreement without prior written consent from the Company.\n",
      "6.\tGoverning Law. This Agreement is governed by the laws of the State of Delaware.\n",
      "7.\tEntire Agreement. This Agreement supersedes all prior agreements between the parties.\n",
      "8.\tAmendments. This Agreement cannot be modified except in writing signed by both parties.\n",
      "9.\tCounterparts. This Agreement may be executed in counterparts, each of which shall be deemed an original.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "you: explain why there are no ambiguities or conflicting terms now in this new contract\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "AI Assistant: There are no ambiguities or conflicting terms now because the \"Duties\" section is more specific about what John Doe's responsibilities will be, and the \"Compensation\" section makes it clear that John Doe will receive the annual bonus that he is expecting.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "you: q\n"
     ]
    }
   ],
   "source": [
    "prompt = \"<|im_start|>system\\n\" + contract + \"\\n<|im_end|>\\n\"\n",
    "\n",
    "while True:\n",
    "    \n",
    "    query = input(\"you:\")\n",
    "    if query == 'q':\n",
    "        break   \n",
    "    user_input = \"<|im_start|>user\\n\" + query + \"\\n<|im_end|>\\n<|im_start|>assistant\\n\"\n",
    "    prompt+=user_input\n",
    "    output = openai.Completion.create(\n",
    "          engine=\"test1\",\n",
    "          prompt=prompt,\n",
    "          temperature=0,\n",
    "          max_tokens=2000,\n",
    "          top_p=0.95,\n",
    "          frequency_penalty=0,\n",
    "          presence_penalty=0,\n",
    "          stop=[\"<|im_end|>\"])\n",
    "    print('\\n')\n",
    "    print('AI Assistant: ' + output[\"choices\"][0][\"text\"].strip() + '\\n')\n",
    "    response = output[\"choices\"][0][\"text\"].strip() + \"\\n<|im_end|>\\n\"\n",
    "    prompt+=response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "bfecdb94-ed55-4585-abab-c0833cda22ea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The clause that states \"ABC agrees not to sell any products to any customers who have purchased products from our competitors within the past six months\" could violate antitrust laws.\n"
     ]
    }
   ],
   "source": [
    "contract = \"\"\"\n",
    "This agreement (\"Agreement\") is made and entered into as of the date of execution by and between ABC Corporation (\"ABC\") and XYZ Company (\"XYZ\").\n",
    "\n",
    "WHEREAS, ABC is engaged in the business of manufacturing and selling widgets, and XYZ desires to purchase widgets from ABC for resale to its customers;\n",
    "\n",
    "NOW, THEREFORE, in consideration of the premises and mutual covenants herein contained, the parties agree as follows:\n",
    "\n",
    "Sale of Products. ABC agrees to sell and deliver to XYZ and XYZ agrees to purchase and receive from ABC, widgets as specified in each purchase order issued by XYZ and accepted by ABC.\n",
    "\n",
    "Price and Payment. The price for the widgets shall be as set forth in the applicable purchase order. Payment shall be due within 30 days of the invoice date.\n",
    "Non-Competition. ABC agrees not to sell any products to any customers who have purchased products from our competitors within the past six months.\n",
    "Warranty. ABC warrants that the widgets sold hereunder will conform to the specifications set forth in each purchase order and will be free from defects in material and workmanship for a period of one year from the date of delivery.\n",
    "Limitation of Liability. ABC's liability for any breach of this Agreement or any warranty provided hereunder shall be limited to the purchase price of the widgets.\n",
    "Governing Law. This Agreement shall be governed by and construed in accordance with the laws of the State of Delaware.\n",
    "\n",
    "IN WITNESS WHEREOF, the parties have executed this Agreement as of the date first above written.\n",
    "\n",
    "ABC Corporation\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "response = openai.Completion.create(\n",
    "  engine=\"test1\",\n",
    "  prompt= contract + \"Analyze this contract and tell me whether there are clauses that might violate the antitrust laws. Make sure to highlight those clauses.\",\n",
    "  temperature=0,\n",
    "  max_tokens=1968,\n",
    "  top_p=0.5,\n",
    "  frequency_penalty=0,\n",
    "  presence_penalty=0,\n",
    "  best_of=1,\n",
    "  stop=None)\n",
    "\n",
    "print(response[\"choices\"][0][\"text\"].strip())"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c6da3585-bb4e-4766-a794-416b48db3ff4",
   "metadata": {},
   "source": [
    "## Providing contracts templates"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "514b7d16-652a-40c6-a884-c2c3f2a206a0",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Service Delivery Agreement\n",
      "\n",
      "This Service Delivery Agreement (\"Agreement\") is entered into on 1/9/2023, by and between Supplier ABC, with a mailing address of 123 Main Street, Italy (\"Provider\"), and Company XYZ, with a mailing address of 456 Elm Street, Italy (\"Client\").\n",
      "\n",
      "Description of Services\n",
      "\n",
      "Provider shall install, configure, and maintain Company's IT infrastructure in accordance with the terms and conditions of this Agreement.\n",
      "\n",
      "Start Date\n",
      "\n",
      "This Agreement shall commence on 1/9/2023.\n",
      "\n",
      "Duration\n",
      "\n",
      "This Agreement shall continue for a period of three (3) years, unless earlier terminated in accordance with the provisions of this Agreement.\n",
      "\n",
      "Payment Terms\n",
      "\n",
      "Client shall pay Provider within 30 days after receipt of an invoice from Provider. All invoices shall be sent to Client's attention at 456 Elm Street, Italy.\n",
      "\n",
      "Termination Notice\n",
      "\n",
      "Either party may terminate this Agreement upon 30 days' written notice to the other party.\n",
      "\n",
      "State or Countries\n",
      "\n",
      "This Agreement shall be governed by the laws of Italy.\n",
      "\n",
      "IN WITNESS WHEREOF, the parties have executed this Agreement as of the date first written above.\n",
      "\n",
      "Supplier ABC\n",
      "\n",
      "______________________________\n",
      "\n",
      "Signature\n",
      "\n",
      "______________________________\n",
      "\n",
      "Typed or Printed Name\n",
      "\n",
      "______________________________\n",
      "\n",
      "Title\n",
      "\n",
      "Company XYZ\n",
      "\n",
      "______________________________\n",
      "\n",
      "Signature\n",
      "\n",
      "______________________________\n",
      "\n",
      "Typed or Printed Name\n",
      "\n",
      "______________________________\n",
      "\n",
      "Title\n"
     ]
    }
   ],
   "source": [
    "service_provider = \"Supplier ABC\"\n",
    "client = \"Company XYZ\"\n",
    "services_description = \"installation, configuration, and maintenance of Company's IT infrastructure\" \n",
    "start_date = \"1/9/2023\"\n",
    "duration = \"Three (3) years\"\n",
    "payment_terms = f\"Within 30 days after receipt of an invoice from {service_provider}\"\n",
    "termination_notice = \"30 days\"\n",
    "state = \"Italy\"\n",
    "\n",
    "\n",
    "response = openai.Completion.create(\n",
    "  engine=\"test1\",\n",
    "  prompt= f\"Generate a Service Delivery Agreement with the following elements: Service Provider: {service_provider}, Client: {client}, Description of Services: {services_description}, Start Date: {start_date}, Duration: {duration}, Payment terms: {payment_terms}, Termination notice: {termination_notice}, State or Countries: {state}\",\n",
    "  temperature=0,\n",
    "  max_tokens=1968,\n",
    "  top_p=0.5,\n",
    "  frequency_penalty=0,\n",
    "  presence_penalty=0,\n",
    "  best_of=1,\n",
    "  stop=None)\n",
    "\n",
    "print(response[\"choices\"][0][\"text\"].strip())\n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "73d87f47-1247-4e48-b259-9c1c3c3cf885",
   "metadata": {},
   "source": [
    "## Analyzing language"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "506590d6-7f80-4ecd-8ea2-4a0f4512b95b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "you: what is EPA?\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "AI Assistant: The Environmental Protection Agency (EPA) is a federal agency responsible for protecting human health and the environment. The EPA's regulations on Underground Injection Control (UIC) Class VI wells govern the construction and operation of CCS facilities.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "you: what is the link of EPA with the above contract?\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "AI Assistant: The EPA's regulations on Underground Injection Control (UIC) Class VI wells govern the construction and operation of CCS facilities.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "you: q\n"
     ]
    }
   ],
   "source": [
    "contract = \"\"\"\n",
    "This Carbon Capture and Storage Agreement (\"Agreement\") is made and entered into on 19/03/2023 by and between Company A, a corporation organized under the laws of France, \n",
    "and Company B, a corporation organized under the laws of Italy. The parties agree to collaborate on a CCS project to store 50 tons of CO2 in a saline aquifer located in Southern \n",
    "France using enhanced oil recovery (EOR) techniques. The parties will jointly design, construct, and operate the CCS facility, and will share the costs of the project in accordance \n",
    "with the proportion of their respective equity interests. Company A will provide the CO2 capture, compression, and transportation equipment, while Company B will provide the storage \n",
    "site and injection equipment. Both parties agree to comply with all applicable laws and regulations related to CCS, including the Environmental Protection Agency's (EPA) \n",
    "regulations on Underground Injection Control (UIC) Class VI wells.\n",
    "\"\"\"\n",
    "\n",
    "prompt = \"<|im_start|>system\\n\" + contract + \"\\n<|im_end|>\\n\"\n",
    "\n",
    "#print('AI Assistant: ' + prompt + '\\n')\n",
    "while True:\n",
    "    \n",
    "    query = input(\"you:\")\n",
    "    if query == 'q':\n",
    "        break   \n",
    "    user_input = \"<|im_start|>user\\n\" + query + \"\\n<|im_end|>\\n<|im_start|>assistant\\n\"\n",
    "    prompt+=user_input\n",
    "    output = openai.Completion.create(\n",
    "          engine=\"test1\",\n",
    "          prompt=prompt,\n",
    "          temperature=0,\n",
    "          max_tokens=2000,\n",
    "          top_p=0.95,\n",
    "          frequency_penalty=0,\n",
    "          presence_penalty=0,\n",
    "          stop=[\"<|im_end|>\"])\n",
    "    print('\\n')\n",
    "    print('AI Assistant: ' + output[\"choices\"][0][\"text\"].strip() + '\\n')\n",
    "    response = output[\"choices\"][0][\"text\"].strip() + \"\\n<|im_end|>\\n\"\n",
    "    prompt+=response"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "446723f2-8db4-4f12-a8e9-c6ab69ceb6d2",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "# Call Center analytics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b091b7e4-bea3-4756-b47b-8779769980b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import re\n",
    "import requests\n",
    "import sys\n",
    "import os\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "88780c50",
   "metadata": {},
   "outputs": [],
   "source": [
    "transcript = \"Operator: Good morning, thank you for calling the auto insurance company, my name is John, how can I assist you today?\\nCustomer: Yes, hi, I just noticed a dent on the side of my car and I have no idea how it got there. There were no witnesses around and I'm really frustrated.\\nOperator: I'm sorry to hear that, I understand how frustrating it can be. Can you please provide me with your name and policy number so I can look up your account?\\nCustomer: Yes, I’m Mario Rossi and the policy number is 123456.\\nOperator: Thank you Mr. Rossi, let me take a look. I see that you've called earlier today, was there an issue with that call?\\nCustomer: Yes, I was on hold for over an hour and the issue was not resolved. I'm really not happy about it.\\nOperator: I'm sorry about that, let me assure you that we value your time and we'll do our best to assist you today. As for the dent on your car, I'd like to inform you that our policy does cover accidental damage like this. I can help you file a claim and connect you with one of our trusted repair shops in your area. Would you like me to proceed with that?\\nCustomer: Yes, please. That would be great.\\nOperator: Thank you for your cooperation. I'm now processing your claim and I'll be sending you an email with the next steps to follow. Please let me know if you have any other questions or concerns.\\nCustomer: Thank you, I appreciate your help.\\nOperator: You're welcome. Have a great day!\\n\\n\\n\"\n",
    "\n",
    "\n",
    "response = openai.Completion.create(\n",
    "  engine=\"test1\",\n",
    "  prompt= transcript + \"Extract the following information from the above text:\\n Name and Surname\\nReason for calling\\n Policy Number\\n Resolution \\n\\n. The ouput format should be JSON\",\n",
    "  temperature=1,\n",
    "  max_tokens=1968,\n",
    "  top_p=0.5,\n",
    "  frequency_penalty=0,\n",
    "  presence_penalty=0,\n",
    "  best_of=1,\n",
    "  stop=None)\n",
    "\n",
    "print(response[\"choices\"][0][\"text\"].strip())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "07e5c407-4da2-4dad-b436-7b37f858acc8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The customer is initially negative because they are frustrated. They were on hold for a long time and their issue was not resolved.\n"
     ]
    }
   ],
   "source": [
    "response = openai.Completion.create(\n",
    "  engine=\"test1\",\n",
    "  prompt= transcript + \"What is the initial and final sentiment of the conversation?\",\n",
    "  temperature=1,\n",
    "  max_tokens=1968,\n",
    "  top_p=0.5,\n",
    "  frequency_penalty=0,\n",
    "  presence_penalty=0,\n",
    "  best_of=1,\n",
    "  stop=None)\n",
    "\n",
    "print(response[\"choices\"][0][\"text\"].strip())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "d194e3b3-0979-40b4-84d7-b5c331fa233f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "as follows:\n",
      "\n",
      "{\n",
      "  \"Name and Surname\": \"Mario Rossi\",\n",
      "  \"Reason for calling\": \"To file a claim for accidental damage\",\n",
      "  \"Policy Number\": \"123456\",\n",
      "  \"Resolution\": \"The issue was resolved and the customer was assisted with filing a claim\",\n",
      "  \"Initial Sentiment\": \"Frustration\",\n",
      "  \"Reason for initial Sentiment\": \"The customer was frustrated because they did not know how the damage occurred and there were no witnesses\",\n",
      "  \"Final sentiment\": \"Satisfied\",\n",
      "  \"Reason for final sentiment\": \"The customer was assisted with filing a claim and was given information on the next steps to follow\",\n",
      "  \"Contact center improvement\": \"Reduce wait time for customers\"\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "response = openai.Completion.create(\n",
    "  engine=\"test1\",\n",
    "  prompt= transcript + \"\"\"Extract the following information from the above text:\\n Name and Surname\\nReason for calling\n",
    "  \\n Policy Number\n",
    "  \\n Resolution\n",
    "  \\n Initial Sentiment\n",
    "  \\n Reason for initial Sentiment\n",
    "  \\n Final sentiment\\n Reason for final sentiment\\n Contact center improvement \\n \\n\\n. The ouput format should be JSON\"\"\",\n",
    "  temperature=1,\n",
    "  max_tokens=1968,\n",
    "  top_p=0.5,\n",
    "  frequency_penalty=0,\n",
    "  presence_penalty=0,\n",
    "  best_of=1,\n",
    "  stop=None)\n",
    "\n",
    "print(response[\"choices\"][0][\"text\"].strip())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "397cea8d-0248-4bb5-8b8c-53223081150d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is a claim handling issue.\n"
     ]
    }
   ],
   "source": [
    "response = openai.Completion.create(\n",
    "  engine=\"test1\",\n",
    "  prompt= transcript + \"\"\"classify the above text in one of the following: reporting issue, \n",
    "  claim handling -  and general inquiry.\"\"\",\n",
    "  temperature=1,\n",
    "  max_tokens=1968,\n",
    "  top_p=0.5,\n",
    "  frequency_penalty=0,\n",
    "  presence_penalty=0,\n",
    "  best_of=1,\n",
    "  stop=None)\n",
    "\n",
    "print(response[\"choices\"][0][\"text\"].strip())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "51338149-0bc8-4d23-9f51-cfff18410fa9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "    \"name\": \"Mario Rossi\",\n",
      "    \"reason_for_calling\": \"To report a dent on the side of his car\",\n",
      "    \"policy_number\": \"123456\",\n",
      "    \"resolution\": \"The operator helped file a claim and connect the customer with a trusted repair shop in the area.\",\n",
      "    \"initial_sentiment\": \"Frustration\",\n",
      "    \"reason_for_initial_sentiment\": \"The customer was frustrated because he did not know how the dent got there and there were no witnesses around.\",\n",
      "    \"final_sentiment\": \"Satisfaction\",\n",
      "    \"reason_for_final_sentiment\": \"The customer was satisfied because the operator was able to help him file a claim and connect him with a trusted repair shop.\",\n",
      "    \"contact_center_improvement\": \"The customer would like the contact center to value his time more and not keep him on hold for long periods of time.\",\n",
      "    \"category\": \"Claim Handling\"\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "response = openai.Completion.create(\n",
    "  engine=\"test1\",\n",
    "  prompt= transcript + \n",
    "    \"\"\"Extract the following information from the above text:\\n Name and Surname\\nReason for calling\n",
    "    \\n Policy Number\\n Resolution\\n Initial Sentiment\\n Reason for initial Sentiment\\n Final sentiment\n",
    "    \\n Reason for final sentiment\\n Contact center improvement\\n Category (choose among reporting issue, \n",
    "    claim handling and general inquiry) \\n \\n\\n. Return the output in JSON.\"\"\",\n",
    "  temperature=1,\n",
    "  max_tokens=1968,\n",
    "  top_p=0.5,\n",
    "  frequency_penalty=0,\n",
    "  presence_penalty=0,\n",
    "  best_of=1,\n",
    "  stop=None)\n",
    "\n",
    "print(response[\"choices\"][0][\"text\"].strip())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "ebe4296b-5cfc-4615-b128-cd4861009738",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "with open('json_data.json', 'w') as outfile:\n",
    "    outfile.write(response[\"choices\"][0][\"text\"].strip())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "f3f79d37-33a6-4607-8d3d-0f48acc7d509",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': 'Mario Rossi',\n",
       " 'reason_for_calling': 'To report a dent on the side of his car',\n",
       " 'policy_number': '123456',\n",
       " 'resolution': 'The operator helped file a claim and connect the customer with a trusted repair shop in the area.',\n",
       " 'initial_sentiment': 'Frustration',\n",
       " 'reason_for_initial_sentiment': 'The customer was frustrated because he did not know how the dent got there and there were no witnesses around.',\n",
       " 'final_sentiment': 'Satisfaction',\n",
       " 'reason_for_final_sentiment': 'The customer was satisfied because the operator was able to help him file a claim and connect him with a trusted repair shop.',\n",
       " 'contact_center_improvement': 'The customer would like the contact center to value his time more and not keep him on hold for long periods of time.',\n",
       " 'category': 'Claim Handling'}"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "# Opening JSON file\n",
    "f = open('json_data.json')\n",
    "\n",
    "# returns JSON object as\n",
    "# a dictionary\n",
    "data = json.load(f)\n",
    "data"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
